#include <iostream>
#include <memory>
#include <spdlog/spdlog.h>
#include <yaml-cpp/yaml.h>
#include "config_manager.h"
#include "market_making_strategy.h"
#include "questdb_backtest.h"
#include "backtest/backtest_example.h"

using namespace hft;

int main(int argc, char* argv[]) {
    try {
        // 加载配置
        auto& config = ConfigManager::getInstance();
        if (!config.loadConfig("config.yaml")) {
            std::cerr << "Failed to load configuration" << std::endl;
            return 1;
        }

        // 初始化日志
        auto log_config = config.getNode("logging");
        spdlog::set_level(spdlog::level::from_str(log_config["level"].as<std::string>()));
        spdlog::set_pattern(log_config["format"].as<std::string>());
        
        auto file_logger = spdlog::basic_logger_mt("file_logger", 
            log_config["file"].as<std::string>());
        spdlog::set_default_logger(file_logger);

        // 创建回测配置
        BacktestConfig backtest_config;
        backtest_config.start_date = "2024-01-01";
        backtest_config.end_date = "2024-03-01";
        backtest_config.initial_capital = 1000000.0;
        backtest_config.commission_rate = 0.0003;  // 0.03%
        backtest_config.slippage = 0.0001;         // 0.01%
        backtest_config.use_real_price = true;
        backtest_config.symbols = {"cu2403", "al2403"};

        // 创建回测系统
        auto backtest = std::make_unique<QuestDBBacktest>(backtest_config);
        if (!backtest->initialize()) {
            spdlog::error("Failed to initialize backtest system");
            return 1;
        }

        // 加载历史数据
        if (!backtest->loadData()) {
            spdlog::error("Failed to load historical data");
            return 1;
        }

        // 创建策略
        MarketMakingParams strategy_params;
        auto strategy_config = config.getNode("trading.strategy.parameters");
        strategy_params.spread_multiplier = strategy_config["spread_multiplier"].as<double>();
        strategy_params.min_spread = strategy_config["min_spread"].as<double>();
        strategy_params.max_position = strategy_config["max_position"].as<int>();
        strategy_params.order_refresh_interval = strategy_config["order_refresh_interval"].as<int>();

        auto strategy = std::make_shared<MarketMakingStrategy>("market_maker", strategy_params);

        // 运行回测
        spdlog::info("Starting backtest...");
        auto result = backtest->run(strategy);

        // 打印回测结果
        spdlog::info("Backtest Results:");
        spdlog::info("Total Return: {:.2f}%", result.total_return * 100);
        spdlog::info("Sharpe Ratio: {:.2f}", result.sharpe_ratio);
        spdlog::info("Max Drawdown: {:.2f}%", result.max_drawdown * 100);
        spdlog::info("Win Rate: {:.2f}%", result.win_rate * 100);
        spdlog::info("Profit Factor: {:.2f}", result.profit_factor);
        spdlog::info("Average Trade: {:.2f}", result.avg_trade);
        spdlog::info("Average Holding Time: {:.2f} seconds", result.avg_holding_time);
        spdlog::info("Total Trades: {}", result.total_trades);
        spdlog::info("Winning Trades: {}", result.winning_trades);
        spdlog::info("Losing Trades: {}", result.losing_trades);

        return 0;

    } catch (const std::exception& e) {
        std::cerr << "Fatal error: " << e.what() << std::endl;
        return 1;
    }
} 
